import { defineStore } from 'pinia';
import { 
  batchAddSchedule, 
  batchSaveOrUpdateSchedules, 
  searchSchedules,
  deleteSchedule,
  type ISchedule,
  type IScheduleCondition
} from '@/api/schedule/schedule';

interface ScheduleState {
  scheduleList: ISchedule[];
  loading: boolean;
  error: string | null;
}

export const useScheduleStore = defineStore('schedule', {
  state: (): ScheduleState => ({
    scheduleList: [],
    loading: false,
    error: null
  }),

  getters: {
    // 获取当前部门的所有排班
    getSchedulesByDept: (state) => (deptId: number | string) => {
      return state.scheduleList.filter(schedule => schedule.deptId === deptId);
    },
    
    // 获取某天的排班
    getSchedulesByDay: (state) => (day: string) => {
      return state.scheduleList.filter(schedule => schedule.dutyDay === day);
    },
    
    // 获取某个员工的排班
    getSchedulesByStaff: (state) => (staffName: string) => {
      return state.scheduleList.filter(schedule => 
        schedule.staffName.includes(staffName)
      );
    },

    // 获取员工某天的排班
    getEmployeeDaySchedule: (state) => (staffName: string, day: string) => {
      return state.scheduleList.find(schedule =>
        schedule.staffName === staffName &&
        schedule.dutyDay === day
      );
    }
  },

  actions: {
    // 批量新增排班
    async addSchedules(schedules: ISchedule[]) {
      this.loading = true;
      this.error = null;
      try {
        await batchAddSchedule({ schedules });
        await this.fetchSchedules();
      } catch (err) {
        this.error = (err as Error).message || '批量新增排班失败';
        throw err;
      } finally {
        this.loading = false;
      }
    },

    // 批量新增或更新排班
    async saveOrUpdateSchedules(schedules: ISchedule[]) {
      this.loading = true;
      this.error = null;
      try {
        await batchSaveOrUpdateSchedules({ schedules });
        await this.fetchSchedules();
      } catch (err) {
        this.error = (err as Error).message || '保存排班失败';
        throw err;
      } finally {
        this.loading = false;
      }
    },

    // 查询排班
    async fetchSchedules(condition?: IScheduleCondition) {
      this.loading = true;
      this.error = null;
      try {
        const response = await searchSchedules(condition || {});
        // 适配后端接口数据结构 {code:200, msg:"ok", data: [...]}
        this.scheduleList = response.data || [];
        
      } catch (err) {
        this.error = (err as Error).message || '获取排班数据失败';
        throw err;
      } finally {
        this.loading = false;
      }
    },

    // 删除排班
    async removeSchedule(scheduleId: number | string) {
      this.loading = true;
      this.error = null;
      try {
        await deleteSchedule(scheduleId);
        await this.fetchSchedules();
      } catch (err) {
        this.error = (err as Error).message || '删除排班失败';
        throw err;
      } finally {
        this.loading = false;
      }
    },

    // 重置状态
    reset() {
      this.scheduleList = [];
      this.error = null;
    }
  }
});